package com.glepoch.springbootsecuritymybatis.compoment.execption;


import com.glepoch.springbootsecuritymybatis.bean.RespResultVO;
import com.glepoch.springbootsecuritymybatis.compoment.constant.statuscode.NormalStatusCode;
import com.glepoch.springbootsecuritymybatis.compoment.execption.impl.CommonExecption;
import com.google.common.base.Throwables;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @description: 统一异常处理类
 * @author: ygl
 * @time:
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    public final Log log = LogFactory.getLog(this.getClass());

    @ExceptionHandler({CommonExecption.class})
    public RespResultVO handleException(CommonExecption e) {
        log.info(e.getMessage());
        RespResultVO fail = RespResultVO.fail(e.getCode(), e.getMessage());
        fail.setData(e);
        return fail;
    }

    @ExceptionHandler({RuntimeException.class})
    public RespResultVO handleException(RuntimeException e) {
        String stackTraceAsString = Throwables.getStackTraceAsString(e);
        log.error(stackTraceAsString);
        RespResultVO fail = RespResultVO.fail();
        fail.setData(stackTraceAsString);
        return fail;
    }

    @ExceptionHandler({Exception.class})
    public RespResultVO handleException(Exception e) {
        String stackTraceAsString = Throwables.getStackTraceAsString(e);
        RespResultVO fail = RespResultVO.fail();
        if (e instanceof NoHandlerFoundException) {
            log.error(e.getMessage());
            fail.setCode(NormalStatusCode.NOHANDLER.getCode());
            fail.setMessage(NormalStatusCode.NOHANDLER.getMessage());
            fail.setData(stackTraceAsString);
            return fail;
        }
        log.error(stackTraceAsString);
        fail.setData(stackTraceAsString);
        return fail;
    }
}
